import React, { Component } from 'react';
import { Text, View, Switch } from 'react-native';
import _ from 'lodash';
import StatusIcon from '../../statusIcon';
import styles from '../styles';

function transValue(value, transformer, reverse) {
  if (transformer && (!_.isArray(transformer) || transformer.length < 2)) {
    throw new Error(
      'transformer has got a bad format transformer'
    );
  }
  if (!transformer) {
    return value;
  }
  const [no, yes] = transformer;
  if (!reverse) {
    switch (value) {
      case no: {
        return false;
      }
      case yes: {
        return true;
      }
      default: {
        return false;
      }
    }
  }
  switch (value) {
    case false: {
      return no;
    }
    case true: {
      return yes;
    }
    default: {
      return no;
    }
  }
}

export default class Bool extends Component {
  constructor(props) {
    super(props);
    let value = props.initialValue;
    if (props.transformer) {
      value = transValue(props.initialValue, props.transformer);
    }
    this.state = {
      value
    };
  }
  componentWillReceiveProps(next) {
    if (next.value !== this.props.value) {
      let value = next.value;
      if (next.transformer) {
        value = transValue(next.value, next.transformer);
      }
      this.setState(
        {
          value
        },
        () => {
          if (_.isFunction(this.props.afterChange)) {
            this.props.afterChange(next.value);
          }
        }
      );
    }
  }
  onChange = value => {
    this.props.onChange(transValue(value, this.props.transformer, true));
  };
  render() {
    return (
      <View style={styles.wrap}>
        <View style={styles.label}>
          <Text style={this.props.error && styles.errorLabel}>
            {this.props.label}
          </Text>
        </View>
        <View style={styles.value}>
          <Switch onValueChange={this.onChange} value={this.state.value} />
        </View>
        {this.props.error ? (
          <StatusIcon type="error" msg={parseErrors(this.props.error)} />
        ) : null}
      </View>
    );
  }
}
